package com.congee02.modelshellmvn.client;

import com.alibaba.fastjson.JSON;
import com.congee02.modelshellmvn.adapter.PlateRecognitionRecordAdapter;
import com.congee02.modelshellmvn.anno.NeedSave;
import com.congee02.modelshellmvn.entity.plate.vo.PlateRecognitionResult;
import com.congee02.modelshellmvn.repo.account.PlateRecognitionRecordRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@Component
@Slf4j
public class PlateRecognitionClient {

    @Value("${service.plate.recognition}")
    private String servicePlateRecognitionUrl;

    @javax.annotation.Resource
    private RestTemplate restTemplate;

//    @NeedSave(
//        repo = PlateRecognitionRecordRepository.class, adapter = PlateRecognitionRecordAdapter.class, returnUpdated = false
//    )
    public List<PlateRecognitionResult> recognize(Resource img) {

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", img);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        ResponseEntity<String> jsonResponse = restTemplate.exchange(
                servicePlateRecognitionUrl,
                HttpMethod.POST,
                requestEntity,
                String.class);

        return JSON.parseArray(
                jsonResponse.getBody(), PlateRecognitionResult.class
        );
    }

}
